//
//  UIViewController+Popup.m
//  JSToolkit
//
//  Created by 정재성 on 2013. 11. 10..
//  Copyright (c) 2013년 정재성. All rights reserved.
//

#import "UIViewController+Popup.h"
#import "UIControl+Block.h"

@implementation UIViewController (Popup)

- (void)presentPopupView:(UIView *)view overlay:(BOOL)overlay animated:(BOOL)animated
{
    UIControl *overlayControl = [[UIControl alloc] initWithFrame:self.view.bounds];
    overlayControl.layer.zPosition = 1;
    overlayControl.alpha = 0.0f;
    if (overlay)
        overlayControl.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3f];

    view.center = overlayControl.center;
    [overlayControl addSubview:view];

    __weak UIControl *weakOverlayControl = overlayControl;
    [overlayControl addEventHandler:^(id sender) {
        [UIView setAnimationsEnabled:animated];
        [UIView animateWithDuration:0.5f animations:^{
            weakOverlayControl.alpha = 0.0f;
        } completion:^(BOOL finished) {
            [UIView setAnimationsEnabled:YES];
            [weakOverlayControl removeFromSuperview];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:overlayControl];
    [UIView setAnimationsEnabled:animated];
    [UIView animateWithDuration:0.5f animations:^{
        overlayControl.alpha = 1.0f;
    } completion:^(BOOL finished) {
        [UIView setAnimationsEnabled:YES];
    }];
}

@end
